package com.summer.boss.controller;

import com.summer.boss.auth.JwtInfo;
import com.summer.boss.constant.CommonConstants;
import com.summer.boss.model.req.LoginParams;
import com.summer.boss.model.vo.MenuVO;
import com.summer.boss.service.ISysUserService;
import com.summer.boss.utils.JsonUtil;
import com.summer.boss.utils.RedisUtil;
import com.summer.boss.model.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Set;

/**
 * <p>
 * 平台用户，用于登录系统 前端控制器
 * </p>
 *
 * @author john.wang
 * @since 2021-07-15
 */
@RestController
@RequestMapping("/boss")
@Api(tags = "登录管理")
public class AuthController {

    @Resource
    private ISysUserService userService;



    @ApiOperation("登录")
    @PostMapping("/login")
    public ResponseResult<String> login(@RequestBody LoginParams user) {
        return ResponseResult.success(this.userService.login(user));
    }

    @ApiOperation("登出")
    @GetMapping("/logout")
    public ResponseResult<Boolean> logout() {
        String username = ((JwtInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
        String key = String.format(CommonConstants.USER_PERMISSION, username);
        RedisUtil.delete(key);
        return ResponseResult.success(true);
    }

    @ApiOperation("查询用户权限")
    @GetMapping("/permissions")
    public ResponseResult<Set<MenuVO>> getPermissions() {
        String username = ((JwtInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
        String key = String.format(CommonConstants.USER_PERMISSION, username);
        String permission = RedisUtil.get(key);
        Set<MenuVO> menus = JsonUtil.parseSet(permission, MenuVO.class);
        return ResponseResult.success(menus);
    }

}

